﻿using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomForm.Common.TagHelpers
{
    /// <summary>
    /// 分页TagHelper帮助类
    /// </summary>
    [HtmlTargetElement("pagination")]
    public class PaginationTagHelper : TagHelper
    {
        /// <summary>
        /// 视图上下文
        /// </summary>
        [ViewContext]
        public ViewContext ViewContext { get; set; }
        /// <summary>
        /// 总记录数
        /// </summary>
        [HtmlAttributeName("total-count")]
        public long TotalCount { get; set; } = 0;
        /// <summary>
        /// 总记录数
        /// </summary>
        [HtmlAttributeName("page-param")]
        public string PageParam { get; set; } = "page";
        /// <summary>
        /// 总记录数
        /// </summary>
        [HtmlAttributeName("size-param")]
        public string SizeParam { get; set; } = "size";

        /// <summary>
        /// 渲染分页条码
        /// </summary>
        /// <param name="context"></param>
        /// <param name="output"></param>
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "ul";
            output.Attributes.Add("class", "pagination");

            if (TotalCount == 0)
            {
                await base.ProcessAsync(context, output);
                return;
            };

            var querys = ViewContext.HttpContext.Request.Query;

            //当前页码
            var pageIndex = 1;
            if (querys.Any() && querys.ContainsKey(PageParam) && querys[PageParam].Any(v => !string.IsNullOrEmpty(v)))
            {
                var pageQuery = querys[PageParam].FirstOrDefault(v => !string.IsNullOrEmpty(v));
                pageIndex = Convert.ToInt32(pageQuery ?? $"{pageIndex}");
            }

            //每页数量
            var pageSize = 10;
            if (querys.Any() && querys.ContainsKey(SizeParam) && querys[SizeParam].Any(v => !string.IsNullOrEmpty(v)))
            {
                var sizeQuery = querys[SizeParam].FirstOrDefault(v => !string.IsNullOrEmpty(v));
                pageSize = Convert.ToInt32(sizeQuery ?? $"{pageSize}");
            }

            //总页数
            var pageCount = (int)Math.Ceiling(TotalCount * 1.0f / pageSize * 1.0f);

            //其他查询参数
            var queryParams = $"&{SizeParam}={pageSize}";

            var otherQuerys = querys.Where(kv => kv.Key != PageParam && kv.Key != SizeParam);
            if (otherQuerys.Any())
            {
                queryParams += "&";
                queryParams += string.Join("&", otherQuerys.Select(kv => $"{kv.Key}={kv.Value}").ToArray());
            }

            //分页条码
            var sb = new StringBuilder(string.Empty);

            #region 构造分页样式

            if (pageIndex == 1)
            {
                sb.AppendLine($"<li class=\"disabled\"><span><<</span></li> <li class=\"disabled\"><span><</span></li> ");
            }
            else
            {
                sb.AppendLine($"<li><a href=\"?{PageParam}=1\"><span><<</span></a></li>  <li><a href=\"?{PageParam}={pageIndex - 1}{queryParams}\"><span><</span></a></li> ");
            }

            var pageDaoda = pageIndex < 6 ? 11 : pageIndex > 5 ? pageIndex + 5 : 0;

            for (int i = pageIndex - 5; i < pageDaoda; i++)
            {
                if (i > 0 && i < pageCount + 1)
                {
                    if (i == pageIndex)
                    {
                        sb.AppendLine($" <li class=\"active\"><span>{i}</span></li> ");
                    }
                    else
                    {
                        sb.AppendLine($" <li><a href=\"?{PageParam}={i}{queryParams}\">{i}</a></li> ");
                    }
                }
            }

            if (pageIndex == pageCount)
            {
                sb.AppendLine($" <li class=\"disabled\"><span>></span></li> <li class=\"disabled\"><span>>></span></li>");
            }
            else
            {
                sb.AppendLine($" <li><a href=\"?{PageParam}={pageIndex + 1}{queryParams}\"><span>></span></a></li> <li><a href=\"?{PageParam}={pageCount}{queryParams}\"><span>>></span></a></li>");
            }

            #endregion

            output.Content.AppendHtml(sb.ToString());
            await base.ProcessAsync(context, output);
        }

    }
}
